//Clean the data in Form
function resetForm(){
	$("form:first")[0].reset();
	if($("select[name='select']").length != 0){
	$("select[name='select']").get(0).selectedIndex = 0;
	}
}
var roleNameExistFlag = false;
//show role confirm div
function alertRoleConfirm(eventSrc){

	$(".requiredNotice").empty(); 
	$("#NoticeField").hide(); 
	$(".requiredNotice").show();
	
	var selectOneRoleFlag = false;
	var roleNameEmptyFlag = false;
	var PermissionFlag = false;
	//check select one role
	if($("select[name='select']").attr("selectedIndex") == 0){
		$(".requiredNotice").append("Please select one role!"); 
		selectOneRoleFlag = true;
		return;
	}
	
	if($("#Role").val() == ""){
		$(".requiredNotice").append('Please fill in the mandatory field "Role Name"!'); 
		roleNameEmptyFlag = true;
		return;
	}
	
	if(checkPermission() == false){
		$(".requiredNotice").append('Please assign at least one permission to a role.'); 
		PermissionFlag = true;
		return;
	}
	
	if(eventSrc == "create"){
		checkRoleNameCreateRole();
	}else if(eventSrc == "maintain"){
		checkRoleNameMaintainRole();
	}
	if(!roleNameExistFlag && !selectOneRoleFlag && !roleNameEmptyFlag && !PermissionFlag){
	
	inputRoleInfo();
	
	showDiv();
	}

}

//check permission is selected
function checkPermission(){
	var roles = $("input[name='functionCheckBox']");
	var count=0;
	$.each(roles,function(i){
		if(roles[i].checked == true){
			count++;
		}
	});
	if(count>0)
	{
		return true;
	}else{
		return false;
	}
}

//copy role information to hidden div
function inputRoleInfo(){
	var roleName = $("#Role").attr("value");
	var active = $("#RoleActive").val();
	var table = $("#Permission");
	
	var cloneTable = table.clone();
	cloneTable.attr("id","hiddenPermission");
	cloneTable.attr("class","blueTable span-17");
	collectRoles(cloneTable);
	$("#hiddenPermission").replaceWith(cloneTable);
	//table.eq(0).clone().insertAfter(trNode.find("span[id='hiddenPermission']"));
	$("span[id='hiddenRoleName']").html(roleName);
	$("span[id='hiddenActive']").html(active);

}

//copy selected permissions to hidden div
function collectRoles(cloneTable){
	var roles = cloneTable.find("input[name='functionCheckBox']");
	$.each(roles,function(i){
		roles.eq(i).attr("name","hiddenFunctionCheckBox");
		if(roles[i].checked == false){
			roles.eq(i).parent().remove();
		}
		else
		{
			roles.eq(i).remove();
		}
	});
}

//pop up hidden div
function showRoleDiv() {
  $("#popDiv").fadeIn("slow");
  $("#loadingbg").fadeIn("slow");
}

//set interlacing row color
function roleGridColor(){
	$(".roleBlueTable tr").mouseover(function() {
        $(this).addClass("over");
    }).mouseout(function() {
        $(this).removeClass("over");
    });
	$(".roleBlueTable tr:even").addClass("Do");
    
}

//get functionalities according to the role you selected
function updateFunctionality(){
	var roleData = {
			"id":$("#hiddenRoleID").attr("value"),
			"roleName":$("#Role").attr("value")
	     };
		
	roleData = JSON2.stringify(roleData);
	var url ="/EKMS-web/roleMgt/maintainRole.do?action=updateFunctionality";
	
	 $.ajax({
        url: url,
        data: roleData,
        type: "POST",
        processData: true,
        contentType: "application/json",
        timeout: 20000,
        dataType: "json",
        success: function(res){updateRoleSucc(res);} ,
        error: function() { $("#loadmessage").append("<br/>Error!Please refresh this page."); }
    });
}

//call-back function of updateFunctionality
function updateRoleSucc(data){
	var res = data;
	$(".succTxt").show();
	$("#noticeTxt").append(data.notice);
	
	var roleActive = data.role.maintainRoleForm.roleActive;
	var selectedFunctionalityList = data.role.maintainRoleForm.selectedFunctionalityList;

	var roleActiveDropDown = $("select[name='roleActive']");
	roleActiveDropDown.children().each(function(){
		if($(this).text() == roleActive){
			$(this).attr("selected",true);
		}
	});

	
	var checkBox = $("input[name='functionCheckBox']");
	$.each(checkBox,function(i){
		checkBox[i].checked = false;
	});
	$.each(checkBox,function(i){
		$.each(selectedFunctionalityList,function(j){
			if(checkBox[i].value == selectedFunctionalityList[j].functionalityCode){
				checkBox[i].checked = true;
			}
		});
	});
	
	//resetRoleDialog();
}

//set controls on page enabled
function resetRoleDialog(){
	$("input").attr('disabled',false);
	$("textarea").attr('disabled',false);
	$("select").attr('disabled',false);
	$("#noticeTxt").empty();
	$(".requiredNotice").empty();
	$(".succTxt").hide();
	//$("#loadingPic").hide();

	closeDiv();
}

//close Pop up window
function closeDiv() {
    $("#popDiv").fadeOut("slow");
    $("#loadingbg").hide();
}

//change another role and update the permissions
function changeRole(role){
	var roleID = role.options[role.selectedIndex].value;
	var roleName = role.options[role.selectedIndex].text;
    $("#hiddenRoleID").attr("value",roleID);

    var roleName = role.options[role.selectedIndex].text;
    $("#Role").attr("value",roleName);

    if(roleName == "Admin" || roleName == "Examinee" || roleName == "Manager"
    	|| roleName == "L&C" || roleName == "Recruitment" || roleName == "HR"){
    	$("#Role").attr("readOnly","readOnly");
    	$("#RoleActive").attr("disabled",true);
    }else{
    	$("#Role").attr("readOnly","");
    	checkCurrentRole();
    }
    
    
    
    if(roleID != "-- Please select --")
    {
    	updateFunctionality();
    	//checkRoleNameMaintainRole();
    }
    
    
}

//Check role name exists at create role page
function checkRoleNameCreateRole(){

	$(".requiredNotice").empty();

	var roleData = {
			"roleName":$("#Role").attr("value")
	     };
		
	roleData = JSON2.stringify(roleData);
	var url ="/EKMS-web/roleMgt/createRole.do?action=checkRoleName";
	
	 $.ajax({
        url: url,
        data: roleData,
        type: "POST",
        processData: true,
        contentType: "application/json",
        timeout: 20000,
        dataType: "json",
        success: function(res){checkRoleNameSucc(res);} ,
        error: function() { $("#loadmessage").append("<br/>Error!Please refresh this page.");}
    });
}

//Call-back function of chechRoleNameSucc
function checkRoleNameSucc(data){
	$(".succTxt").show();
	$("#noticeTxt").append(data.notice);
	var roleNameExist = data.role.roleNameExist;
	if(roleNameExist == "Yes"){
		$(".requiredNotice").show();
		$(".requiredNotice").append('The "Role Name" already exist, please fill in again!'); 
		roleNameExistFlag = true;
	}else if(roleNameExist == "No"){
		$(".requiredNotice").hide();
		roleNameExistFlag = false;
	}
}

//Check role name exist at maintainrole page
function checkRoleNameMaintainRole(){
	$(".requiredNotice").empty();
	
	if($("#hiddenRoleID").attr("value") == "" || $("#hiddenRoleID").attr("value") == "-- Please select --"){
		return;
	}
	var roleData = {
			"id":$("#hiddenRoleID").attr("value"),
			"roleName":$("#Role").attr("value")
	     };
		
	roleData = JSON2.stringify(roleData);
	var url ="/EKMS-web/roleMgt/maintainRole.do?action=checkRoleName";
	
	 $.ajax({
        url: url,
        data: roleData,
        type: "POST",
        processData: true,
        contentType: "application/json",
        timeout: 20000,
        dataType: "json",
        success: function(res){checkRoleNameSucc(res);} ,
        error: function() { $("#loadmessage").append("<br/>Error!Please refresh this page.");}
    });
}

//Check role name exist at maintainrole page
function checkCurrentRole(){
	var roleData = {
			"roleName":$("#Role").attr("value")
	     };
		
	roleData = JSON2.stringify(roleData);
	var url ="/EKMS-web/roleMgt/maintainRole.do?action=checkCurrentRole";
	
	 $.ajax({
        url: url,
        data: roleData,
        type: "POST",
        processData: true,
        contentType: "application/json",
        timeout: 20000,
        dataType: "json",
        success: function(res){checkCurrentRoleSucc(res);} ,
        error: function() { $("#loadmessage").append("<br/>Error!Please refresh this page.");}
    });
}

//Call-back function of chechRoleNameSucc
function checkCurrentRoleSucc(data){
	
	var allow = data.role.allow;
	if(allow == "False"){
		$("#RoleActive").attr("disabled",true);
	}else if(allow == "True"){
		$("#RoleActive").attr("disabled",false);
	}
	
}